package com.dji.GSDemo.GaodeMap;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.dji.GSDemo.GaodeMap.Network.MonitorNetConnection;
import com.dji.GSDemo.GaodeMap.UploadPicture.UAVUploadPicture;
import com.dji.GSDemo.GaodeMap.UploadPicture.UAVPictureUploadListener;

import java.io.File;
import java.io.IOException;
import java.util.List;

import dji.common.camera.SettingsDefinitions;
import dji.common.error.DJIError;
import dji.common.util.CommonCallbacks;
import dji.sdk.base.BaseProduct;
import dji.sdk.camera.Camera;
import dji.sdk.media.DownloadListener;
import dji.sdk.media.MediaFile;
import dji.sdk.media.MediaManager;
import dji.sdk.sdkmanager.DJISDKManager;
import dji.thirdparty.okhttp3.Call;
import dji.thirdparty.okhttp3.Callback;
import dji.thirdparty.okhttp3.MediaType;
import dji.thirdparty.okhttp3.MultipartBody;
import dji.thirdparty.okhttp3.OkHttpClient;
import dji.thirdparty.okhttp3.Request;
import dji.thirdparty.okhttp3.RequestBody;
import dji.thirdparty.okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    // 文件下载对话框
    private ProgressDialog mPgsDlgDownload;
    // 媒体管理器
    private MediaManager mMediaManager;
    // 获取面向地面站通信单例类引用
    private final MonitorNetConnection connection = MonitorNetConnection.getInstance();
    // 获取上传图片单例类引用
    private UAVUploadPicture uploader = UAVUploadPicture.getInstance();

    private View.OnClickListener clickListener = v -> {
        switch (v.getId()) {
            case R.id.btn_waypoint1:
//                startActivity(MainActivity.this, Waypoint1Activity.class);
                // 用来测试新函数。
                uploader.getLastMediaList();
                uploader.prepareBeforeRun_getLastMediaList();
                break;
            case R.id.btn_my_waypoint:
                startActivity(MainActivity.this, MyWaypointActivity.class);
                break;
            case R.id.btn_update_IP:
                setIPAddr();
                break;
            case R.id.btn_pic_manager:
                create_pic_manager();
                break;
            case R.id.btn_download_all:
                download_all();
                break;
            case R.id.btn_upload_pic_to_GCS:
                upload_pic_to_GCS();
                break;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_waypoint1).setOnClickListener(clickListener);
        findViewById(R.id.btn_my_waypoint).setOnClickListener(clickListener);
        findViewById(R.id.btn_pic_manager).setOnClickListener(clickListener);
        findViewById(R.id.btn_download_all).setOnClickListener(clickListener);
        findViewById(R.id.btn_upload_pic_to_GCS).setOnClickListener(clickListener);
        showIP();

        // 初始化文件下载对话框
        mPgsDlgDownload = new ProgressDialog(MainActivity.this);
        mPgsDlgDownload.setTitle("媒体文件下载中...");
        mPgsDlgDownload.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mPgsDlgDownload.setCanceledOnTouchOutside(false);
        mPgsDlgDownload.setCancelable(true);
        mPgsDlgDownload.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (mMediaManager != null) {
                    mMediaManager.exitMediaDownloading();
                }
            }
        });

        // 初始化图片传输单例类。
        String ipAddr = connection.getIpAddress();
        // 添加图片传输监听器。
        uploader.addListener(pictureUploadListener);
        // 设置图片传输单例类中的CoUAS的IP值。
        uploader.setIP(ipAddr);
    }

    // 定义图片传输监听器。
    private final UAVPictureUploadListener pictureUploadListener = new UAVPictureUploadListener() {
        @Override
        public void onLog(String message) {
            showToast(message);
        }

        @Override
        public void onDownloadComplete() {

        }
    };

    public static void startActivity(Context context, Class activity) {
        Intent intent = new Intent(context, activity);
        context.startActivity(intent);
    }

    // 设置IP
    private void setIPAddr(){
        // IP设置文本框
        final EditText editText = new EditText(this);
        editText.setInputType(InputType.TYPE_CLASS_TEXT);  // 只能输入纯数字
        editText.setText(connection.getIpAddress());
        // 弹出设置IP对话框
        new AlertDialog.Builder(this)
                .setTitle("地面站IP")
                .setView(editText)
                .setPositiveButton("修改", (dialog, which) -> {
                    String ip = editText.getText().toString();
                    connection.setIP(ip);
                    uploader.setIP(ip);
                })
                .setNegativeButton("退出", null)
                .show();
    }

    private void create_pic_manager(){
        Camera camera = getCamera();
        if (camera == null) {
            showToast("相机对象获取失败!");
            return;
        }
        if (!camera.isMediaDownloadModeSupported()) {
            showToast("当前相机不支持MediaDownload模式!");
            return;
        }
        // 弹出MediaDownloadActivity
        Intent i = new Intent(MainActivity.this, MediaDownloadActivity.class);
        startActivity(i);
    }

    private void download_all(){
        // 使用私有函数下载图片到APP。
//        initMediaManager();

        // 使用图片传输单例类下载并上传图片。
        uploader.download_all();

//        unsetMediaManager();
    }

    private void upload_pic_to_GCS(){
        new HTTPSocketThread_send_picture_to_GCS().start();
    }

    private class HTTPSocketThread_send_picture_to_GCS extends Thread {
        @Override
        public void run() {
            send_picture_to_GCS_by_http(); // 从服务端监听命令
        }
    }
    private void send_picture_to_GCS_by_http(){
//        String url = "http://"+ipAddr+":3000/loadUserPoint";
//        final OkHttpClient client2 = new OkHttpClient();
////没有上传参数传输至后台
//        RequestBody requestBody = new FormBody.Builder()
//                .build();
//
//        final Request request2 = new Request.Builder()
//                .url(url)
//                .post(requestBody)
//                .build();
//        Response response = null;
//        try {
//            response = client2.newCall(request2).execute();
//            if (response.isSuccessful()) {
////若后台返回JsonArray格式，JsonArray格式[{name:"heihei",age:24,sex:"男"},{name:"haha",age:20,sex:"女"}]
//                InputStream ins = response.body().byteStream();
//                BufferedReader br = new BufferedReader(new InputStreamReader(ins));
//                String line;
//                //StringBuilder 缓存区 StringBuffer
//                StringBuilder builder = new StringBuilder();
//                while ((line = br.readLine()) != null) {
//                    builder.append(line);
//                }
//                br.close();
//                int i = 0;
//                JSONArray jsarr = new JSONArray(builder.toString());
//                showToast("from http: "+jsarr.toString());
//                Thread.sleep(5000);
////                //若后台返回字符串
////                ResponseBody responseBody = response.body();
////                BufferedSource source = response.body().source();
////                MediaType contentType = responseBody.contentType();
////                Charset charset = Util.bomAwareCharset(source, contentType.charset(Util.UTF_8));
////                String var3 = source.readString(charset);
////                showToast("from http: "+var3);
////                Thread.sleep(5000);
//            }
//            else{
//                showToast("clients is failed");
//                Thread.sleep(5000);
//            }
//        }catch (Exception ex) {
//            // 键为null或使用json不支持的数字格式(NaN, infinities)
//            throw new RuntimeException(ex);
//        }
        try{
            String url = "http://"+getIP()+":3000/image";
//            url = "http://"+ipAddr+":3000/image";
            Thread.sleep(5000);
            String buf = "";
            int whilenum = 0;
            //if(task_done)
            // 设置待传输图片所在文件夹路径。
            File downloadDir = new File(getExternalFilesDir(null) + "/media/");
            String[] files = downloadDir.list();
            int filesNum = files.length;
            for (int ifile = 0; ifile < filesNum; ifile++) {
                OkHttpClient client = new OkHttpClient();
                MultipartBody.Builder builder = new
                        MultipartBody.Builder().setType(MultipartBody.FORM);
                File file = new File(getExternalFilesDir(null) + "/media/" + files[ifile]);
                if (file != null) {
                    builder.addFormDataPart("file", file.getName(),
                            RequestBody.create(MediaType.parse("png"), file));
                    //添加其他参数
                    //builder.addFormDataPart("id", id);
                }
                MultipartBody multipartBody = builder.build();
                //构建请求
                final Request request = new Request.Builder()
                        .url(url)//请求地址
                        .post(multipartBody)//添加请求体参数
                        .build();
                //请求回调
                Call call = client.newCall(request);
                final int filenum = ifile;
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
//                        Log.e("TAG","上传失败"+e.getLocalizedMessage());
                        showToast("TAG "+"文件"+Integer.toString(filenum)+" 上传失败"+e.getLocalizedMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseStr = response.body().string();
//                        Log.e("TAG","上传成功"+responseStr);
                        showToast("TAG "+"文件"+Integer.toString(filenum)+" 上传成功"+responseStr);
                    }
                });
            }
        }catch (Exception ex) {
            // 键为null或使用json不支持的数字格式(NaN, infinities)
            throw new RuntimeException(ex);
        }

    }


    // 下载媒体文件
    private void download(MediaFile mMediaFile) {
        // 设置下载位置
        File downloadDir = new File(getExternalFilesDir(null) + "/media/");
        // 开始下载文件
        mMediaFile.fetchFileData(downloadDir, null, new DownloadListener<String>() {
            @Override
            public void onFailure(DJIError error) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPgsDlgDownload.cancel();
                    }
                });
                showToast("文件下载失败!");
            }
            @Override
            public void onProgress(long total, long current) {
            }
            @Override
            public void onRateUpdate(final long total, final long current, long persize) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int tmpProgress = (int) (1.0 * current / total * 100);
                        mPgsDlgDownload.setProgress(tmpProgress);
                    }
                });
            }
            @Override
            public void onStart() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPgsDlgDownload.incrementProgressBy(-mPgsDlgDownload.getProgress()); // 将下载进度设置为0
                        mPgsDlgDownload.show();
                    }
                });
            }
            @Override
            public void onSuccess(String filePath) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        mPgsDlgDownload.dismiss();
                    }
                });
                showToast("文件下载成功,下载位置为:" + filePath);

            }

            @Override
            public void onRealtimeDataUpdate(byte[] bytes, long l, boolean b) {

            }
        });
    }

    // 初始化媒体管理器
    private void initMediaManager() {
        Camera camera = getCamera();
        // 判断相机对象非空，且支持媒体下载模式
        if (camera == null) {
            showToast("相机对象获取错误!");
            return;
        }
        if (!camera.isMediaDownloadModeSupported()) {
            showToast("当前相机不支持媒体下载模式!");
            return;
        }
        // 获取媒体管理器
        mMediaManager = camera.getMediaManager();
        if (mMediaManager == null) {
            showToast("媒体管理器错误!");
            return;
        }
        // 设置当前相机模式为媒体下载模式
        camera.setMode(SettingsDefinitions.CameraMode.MEDIA_DOWNLOAD, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    showToast("相机模式设置错误!" + djiError.getDescription());
                    return;
                }
                showToast("开始获取媒体列表!");
                // 开始获取媒体文件列表
                mMediaManager.refreshFileListOfStorageLocation(SettingsDefinitions.StorageLocation.SDCARD, new CommonCallbacks.CompletionCallback() {
                    @Override
                    public void onResult(DJIError djiError) {
                        if (djiError != null) {
                            showToast("获取媒体文件列表错误!" + djiError.getDescription());
                            return;
                        }
                        // 媒体文件列表
                        List<MediaFile> mediaFiles = mMediaManager.getSDCardFileListSnapshot();
//                        mPgsDlgDownload.incrementProgressBy(-mPgsDlgDownload.getProgress()); // 将下载进度设置为0
//                        mPgsDlgDownload.show();
                        int fileNum = mediaFiles.size();
                        showToast("有" + Integer.toString(fileNum)+"个文件");
//                        Thread downloadFile = new downloadFileThread(mediaFiles.get(0));
//                        downloadFile.start();
                        for(int i = 0; i < fileNum; i++){
//                            download(mediaFiles.get(i));
//                        for(int i = 0; i < 1; i++){
//                            while(isDownloading){
//                                showToast("第" + Integer.toString(i)+"个文件 is waiting.");
//                                sleep(5000);
//                            }
//                            while(downloadFile.isAlive()){
//
//                            }
//                            isDownloading = true;
                            Thread downloadFile = new downloadFileThread(mediaFiles.get(i));
                            downloadFile.start();
//                            int tmpProgress = (int) (1.0 * (i+1) / fileNum * 100);
//                            mPgsDlgDownload.setProgress(tmpProgress);
                        }
//                        mPgsDlgDownload.dismiss();
//                        unsetMediaManager();
                    }
                });

            }
        });
    }

    private class downloadFileThread extends Thread {
        MediaFile file;
        boolean isDownloading = false;
        public downloadFileThread(MediaFile aFile){
            file = aFile;
        }
        @Override
        public void run() {
            synchronized(this){
                if(!isDownloading){
                    download(file); // 从服务端监听命令
                }
            }
        }
    }

    // 重置媒体管理器
    private void unsetMediaManager() {
        // 重置媒体管理器对象
        if (mMediaManager != null) {
            // 如果正在回放视频，则停止回放。
            mMediaManager.stop(null);
            // 如果正在下载媒体，则取消下载。
            mMediaManager.exitMediaDownloading();
        }

        // 相机退出媒体下载模式
        Camera camera = getCamera();
        if (camera != null) {
            camera.setMode(SettingsDefinitions.CameraMode.SHOOT_PHOTO, new CommonCallbacks.CompletionCallback() {
                @Override
                public void onResult(DJIError djiError) {
                    if (djiError != null){
                        showToast("修改相机模式失败!" + djiError.getDescription());
                    }
                }
            });
        }

    }

    private void showIP(){
        ((TextView)findViewById(R.id.tv_ip)).setText("ip in Connection class is " + getIP());
    }

    public String getIP(){
        return MonitorNetConnection.getInstance().getIpAddress();
    }

    private void showToast(final String toastMsg) {

        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), toastMsg, Toast.LENGTH_LONG).show();
            }
        });

    }

    // 获得无人机的相机对象
    private Camera getCamera() {
        BaseProduct product = DJISDKManager.getInstance().getProduct();
        if (product != null && product.isConnected()) {
            return product.getCamera();
        }
        return null;
    }
}
